package com.zhugang.week03;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @program algorithms
 * @description: myStack2
 * @author: chanzhugang
 * @create: 2022/06/04 16:04
 */
public class MyStack2 {

    Queue<Integer> queue;

    /**
     * 225. 用队列实现栈
     * push：直接入栈
     * pop、top倒腾队列
     */
    public MyStack2() {
        queue = new LinkedList<>();
    }

    public void push(int x) {
        queue.offer(x);
    }

    public int pop() {
        int n = queue.size();
        for (int i = 0; i < n - 1; i++) {
            queue.offer(queue.poll());
        }
        return queue.poll();
    }

    public int top() {
        int n = queue.size();
        for (int i = 0; i < n - 1; i++) {
            queue.offer(queue.poll());
        }
        Integer result = queue.poll();
        // 放在末尾，和最开始位置不变
        queue.offer(result);
        return result;
    }

    public boolean empty() {
        return queue.isEmpty();
    }

}